import React from 'react';
import { connect } from 'dva';
import { Link, browserHistory } from 'dva/router';
import { Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message } from 'antd';
const R = require('ramda');
import moment from 'moment'
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
import OperatorConstant from "../../../utils/OperatorConstant";
import OpeninvoiceDetail from '../../../components/drawback/OpeninvoiceDetail';
import RightBox from "../../../components/commons/RightBox";
import RIGHT from "../../../utils/RightConstants";
import Preinvoiceopen from '../../../components/drawback/Preinvoiceopen';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

export default connect(({ invoice, recinvoices }) => ({ invoice, recinvoices }))(
    Form.create()(class invoice extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                type: "",

            }
        }

        componentDidMount() {
            this.props.dispatch({
                type: 'invoice/getInvoicesList',
            });
        }


        handleResetFields = () => {
            if (this.editCustomer) this.editCustomer.handleResetFields();
        }

        handleCancel = (flag) => {
            if (flag) {
                this.handleResetFields();
            }
        }

        onEdit = (record, type, disabled) => {
            this.handleOpen(record, type, disabled);
        }

        addPreinvoiceopen = (record, type) => {
            this.props.dispatch({ type: 'recinvoices/getInoviceheaderByOrderId', payload: { orderId: record.id } });
            this.props.dispatch({
                type: 'recinvoices/getTaxPreOpenInvoiceByOrderId',
                payload: { orderId: record.id },
            });
            if (this.preinvoiceopen) this.preinvoiceopen.handleOpen(type);
        }

        handleOpen = (record, type, disabled) => {
            this.props.dispatch({ type: 'recinvoices/getInoviceheaderByOrderId', payload: { orderId: record.id } });
            this.props.dispatch({ type: 'recinvoices/getInoviceproductsByOrderId', payload: { orderId: record.id } });
            this.openinvoiceDetail.handleOpen(type, record.id, record.openinvoicestatus, disabled);
        }

        handleSearch = (flag) => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.invoice.page;
            newPage.page = flag ? newPage.page : 1;


            this.props.dispatch({
                type: 'invoice/getInvoicesList',
                payload: {
                    contractno: values.contractno,
                    status: values.status,
                    page: newPage,
                }
            });
            this.setState({ type: values.status });


        };

        handleExport = () => {
            let values = this.props.form.getFieldsValue();

            let status = values.status;
            let contractno = values.contractno;

            this.props.dispatch({
                type: "invoice/exportInvoiceList",
                payload: {
                    openinvoicestatus: R.isNil(status) ? "" : status,
                    contractno: R.isNil(contractno) ? "" : contractno,
                }
            })
        }

        handleCancelPreInvoice = (orderId) => {
            this.props.dispatch({
                type: "invoice/cancelPreInvoice",
                payload: {
                    orderId,
                    onSuccess: () => {
                        this.handleSearch(true);
                    }
                }
            })
        }

        columns = [
            { title: '订单号', dataIndex: 'orderno', key: 'orderno', width: '150px', fixed: true },
            { title: '合同协议号', dataIndex: 'contractno', key: 'contractno' },
            { title: '下单时间', dataIndex: 'orderTime', key: 'orderTime' },
            { title: '放行日期', dataIndex: 'passtime', key: 'passtime' },
            { title: '已放行天数', dataIndex: 'passDate', key: 'passDate' },
            { title: '客户名称', dataIndex: 'companyname', key: 'companyname' },
            { title: '服务专员', dataIndex: 'waiterName', key: 'waiterName' },
            {
                title: '外汇状态', key: 'foxerstatus',
                render(record) {
                    if (record.foxerstatus == 0) {
                        return "未收齐";
                    } else if (record.foxerstatus == 1) {
                        return "已收齐";
                    } else {
                        return "未知";
                    }
                }
            },
            {
                title: '费用是否申报', render(record) {
                    if (record.chargestatus == 0) {
                        return "未完毕";
                    } else if (record.chargestatus == 1) {
                        return "通关已完毕";
                    } else if (record.chargestatus == 2) {
                        return "跟单已完毕";
                    } else {
                        return "未知";
                    }
                }
            },
            {
                title: '预开票',
                render(record) {
                    return record.isperopeninvoice === "2" ? "是" : "否";
                }
            },
            {
                title: '服务类型',
                render(record) {
                    return record.declarationstyle === "2" ? "外综" : "自营";
                }
            },
            {
                title: '操作', width: '200px', fixed: 'right', key: 'key_oprator',

                render: (text, record, index) => {
                    if (record.businessType === '1') {//市场采购不存在所有操作
                        let preInvoice = <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_PRE} split={true}><a href="#" onClick={() => this.addPreinvoiceopen(record, OperatorConstant.add)}>预开票</a></RightBox>
                        preInvoice = record.openinvoicestatus === '0' ? preInvoice : undefined;
                        let preInvoiceDetail = <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_PRE} split={true}><a href="#" onClick={() => this.addPreinvoiceopen(record, OperatorConstant.add, true)}>预开票详情</a></RightBox>
                        preInvoiceDetail = record.isperopeninvoice === '2' && (record.openinvoicestatus === '1' || record.openinvoicestatus === '2') ? preInvoiceDetail : undefined;
                        let doInvoice = <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_GENERATE} split={true}><a href="#" onClick={() => this.onEdit(record, OperatorConstant.openInvoice, false)}>做开票资料</a></RightBox>
                        doInvoice = record.openinvoicestatus === '1' ? doInvoice : undefined;
                        let redoInvoice = <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_REGENERATE} split={true}> <a href="#" onClick={() => this.onEdit(record, OperatorConstant.openInvoice, false)}>重做开票资料</a></RightBox>
                        redoInvoice = record.openinvoicestatus === '2' ? redoInvoice : undefined;
                        let cancelPreInvoice = <Popconfirm onConfirm={this.handleCancelPreInvoice.bind(this, record.id)} okText="是" cancelText="否"
                            placement="leftTop" title={'取消预开票，预开票数据将会被删除且订单会回退到待做开票资料或者未做开票资料，是否继续操作? '}>
                            <a href="#">取消预开票</a>
                        </Popconfirm>
                        cancelPreInvoice = <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_CANCEL} split={true}>{cancelPreInvoice}</RightBox>
                        cancelPreInvoice = record.isperopeninvoice === '2' && (record.openinvoicestatus === '1' || record.openinvoicestatus === '2') ? cancelPreInvoice : undefined;
                        return (
                            <span>
                                {preInvoice}{preInvoiceDetail}{doInvoice}{redoInvoice}{cancelPreInvoice}
                                <a href="#" onClick={() => this.onEdit(record, OperatorConstant.view, true)}>查看</a>
                            </span>
                        );
                    }
                }
            }
        ];

        render() {
            let dataSouce = R.isNil(this.props.invoice.dataSource) ? {} : this.props.invoice.dataSource;
            let taxpreopeninvoice;
            if (this.state.type != "0") {
                taxpreopeninvoice = R.isNil(this.props.recinvoices.taxpreopeninvoice) ? {} : this.props.recinvoices.taxpreopeninvoice;
            }

            let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let time = values.time;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.invoice.page.size,
                total: this.props.invoice.page.totalRow,
                showSizeChanger: true,
                current: this.props.invoice.page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.invoice.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'invoice/getInvoicesList',
                        payload: {
                            contractno: values.contractno,
                            status: values.status,
                            page: newPage,
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.invoice.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'invoice/getInvoicesList',
                        payload: {
                            contractno: values.contractno,
                            status: values.status,
                            page: newPage,
                        }
                    });
                }
            }

            return (
                <div>

                    <Row>
                        <Col span={9}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractno')(<Input placeholder="支持模糊搜索" />)}</FormItem></Col>
                        <Col span={7}>
                            <RightBox resource={RIGHT.DRAW.EXPORTING_TICKETS_LIST}>
                                <Button type="primary" style={{ marginLeft: 35 }} onClick={this.handleExport.bind(this)}>导出开票资料列表</Button>
                            </RightBox>

                        </Col>
                    </Row>

                    <Row>
                        <Col span={9}>
                            <FormItem {...formItemLayout} label={'状态'}>
                                {getFieldDecorator('status', {
                                    initialValue: '0'
                                })(
                                    <RadioGroup style={{ width: 800 }}>
                                        <Radio value='0'>未做开票资料</Radio>
                                        <Radio value='1'>待做开票资料</Radio>
                                        <Radio value='2'>已做开票资料</Radio>
                                    </RadioGroup>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={9} style={{ float: 'left' }}>
                            <Button type="primary" icon="search" style={{ marginLeft: 35 }} onClick={this.handleSearch.bind(this)}>查询</Button>
                        </Col>
                    </Row>

                    <Table rowKey="orderno" dataSource={this.props.invoice.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} />

                    <OpeninvoiceDetail wrappedComponentRef={(inst) => this.openinvoiceDetail = inst} dispatch={this.props.dispatch}
                        handleSearch={this.handleSearch}
                        inoviceproductsList={this.props.recinvoices.inoviceproductsList}
                        totalprice={this.props.recinvoices.totalprice}
                        invoices={this.props.recinvoices.inoviceheader} />

                    <Preinvoiceopen wrappedComponentRef={(inst) => this.preinvoiceopen = inst} dispatch={this.props.dispatch}
                        dataSource={taxpreopeninvoice}
                        recinvoices={this.props.recinvoices}
                        invoices={this.props.recinvoices.inoviceheader}
                        taxpreopeninvoice={this.props.recinvoices.taxpreopeninvoice}
                        handleSearch={this.handleSearch} />


                </div>
            )
        }
    })


)
